// 全局状态管理
const state = {
    apiTypes: new Map(),
    dataTypes: new Map(),
    selectedItems: {
        apiTypes: new Map(),
        dataTypes: new Map()
    },
    trackingEnabled: false
};

// 从private.json加载数据
let privacyData = null;

async function loadPrivacyData() {
    try {
        const response = await fetch('resources/private.json');
        privacyData = await response.json();
        
        // 处理 API 类型
        if (privacyData.APITypes?.items) {
            privacyData.APITypes.items.forEach(category => {
                if (category.xmlKey && category.itemName) {
                    state.apiTypes.set(category.xmlKey, {
                        name: category.itemName,
                        description: category.translationDes || '',
                        reasons: category.items ? category.items.map(item => ({
                            key: item.typeKey,
                            explain: item.explain,
                            translationDes: item.translationDes
                        })) : []
                    });
                }
            });
        }
        
        // 处理数据类型
        if (privacyData.collectionData?.typeList) {
            privacyData.collectionData.typeList.forEach(group => {
                if (group.items) {
                    group.items.forEach(item => {
                        if (item.typeKey) {
                            state.dataTypes.set(item.typeKey, {
                                name: item.typeName || item.typeKey,
                                description: item.translationDes || '',
                                groupName: group.typeGroupName
                            });
                        }
                    });
                }
            });
        }
        
        return privacyData;
    } catch (error) {
        console.error('Error loading privacy data:', error);
        throw error;
    }
}

// 初始化状态
function initializeState() {
    state.apiTypes = new Map();
    state.dataTypes = new Map();
    state.selectedItems = {
        apiTypes: new Map(),
        dataTypes: new Map()
    };
    state.trackingEnabled = false;
}

// DOM 元素
const elements = {
    apiTypesContainer: document.getElementById('apiTypesContainer'),
    dataCollectionContainer: document.getElementById('dataCollectionContainer'),
    addAPITypeBtn: document.getElementById('addAPIType'),
    addDataCollectionBtn: document.getElementById('addDataCollection'),
    noAPITypesMessage: document.getElementById('noAPITypesMessage'),
    noDataCollectionMessage: document.getElementById('noDataCollectionMessage'),
    xmlPreview: document.getElementById('xmlPreview'),
    copyButton: document.getElementById('copyButton'),
    trackingToggle: document.getElementById('trackingToggle')
};

// 创建API Type的收集目的条目
function createPurposeItem(purpose, typeKey = '') {
    const div = document.createElement('div');
    div.className = 'form-check purpose-item';
    div.setAttribute('role', 'button');

    const purposeId = purpose.toLowerCase().replace(/\s+/g, '-');
    const typeKeyDisplay = typeKey ? ` (${typeKey})` : '';

    div.innerHTML = `
        <input class="form-check-input api-purpose-checkbox" type="checkbox" 
               value="NSPrivacyAccessedAPITypeReason${purpose}" 
               data-purpose="${purposeId}">
        <label class="form-check-label" data-purpose="${purposeId}">
            ${purpose}${typeKeyDisplay}
            <i class="bi bi-info-circle ms-2 purpose-info" 
               data-bs-toggle="popover" 
               data-bs-trigger="hover focus"
               data-bs-html="true"
               data-bs-content="<strong>${purpose}</strong><br>${getPurposeDescription(purpose)}<br><br><strong>${getPurposeTranslation(purpose)}</strong><br>${getPurposeTranslationDescription(purpose)}"
               role="button"></i>
        </label>
    `;

    return div;
}

// 统一的点击事件处理
function handlePurposeItemClick(event, container, itemType) {
    // 如果点击的是信息图标或其父元素，不触发选中
    if (event.target.closest('.purpose-info')) {
        return;
    }

    // 检查是否点击了purpose-item或form-check
    const purposeItem = event.target.closest('.purpose-item, .form-check');
    if (!purposeItem) {
        return;
    }

    const checkbox = purposeItem.querySelector(itemType === 'api' ? '.api-purpose-checkbox' : '.purpose-checkbox');
    if (!checkbox || checkbox.disabled) {
        return;
    }

    // 如果点击的是复选框本身，让它自然处理
    if (event.target === checkbox) {
        return;
    }

    // 切换复选框状态
    checkbox.checked = !checkbox.checked;
    checkbox.dispatchEvent(new Event('change', { bubbles: true }));
}

// 事件监听器
function attachEventListeners() {
    elements.addAPITypeBtn.addEventListener('click', addAPITypeItem);
    elements.addDataCollectionBtn.addEventListener('click', addDataTypeCard);
    elements.trackingToggle.addEventListener('change', function(event) {
        state.trackingEnabled = event.target.checked;
        updateXMLPreview();
    });
    elements.copyButton.addEventListener('click', copyXMLToClipboard);

    // API Types事件委托
    elements.apiTypesContainer.addEventListener('click', (event) => {
        handlePurposeItemClick(event, elements.apiTypesContainer, 'api');
    });

    // API Types状态变化
    elements.apiTypesContainer.addEventListener('change', (event) => {
        if (event.target.matches('.api-purpose-checkbox')) {
            const checkbox = event.target;
            const apiTypeItem = checkbox.closest('.api-type-item');
            const apiTypeSelect = apiTypeItem.querySelector('.api-type-select');
            const apiType = apiTypeSelect.value;

            if (!state.selectedItems.apiTypes.has(apiType)) {
                state.selectedItems.apiTypes.set(apiType, new Set());
            }

            const purposes = state.selectedItems.apiTypes.get(apiType);
            if (checkbox.checked) {
                purposes.add(checkbox.value);
            } else {
                purposes.delete(checkbox.value);
            }
            updateXMLPreview();
        }
    });

    // Data Collection事件委托
    elements.dataCollectionContainer.addEventListener('click', (event) => {
        handlePurposeItemClick(event, elements.dataCollectionContainer, 'data');
    });

    elements.dataCollectionContainer.addEventListener('change', (event) => {
        if (event.target.matches('.data-type-select')) {
            handleDataTypeChange(event);
        } else if (event.target.matches('.purpose-checkbox')) {
            handleDataPurposeChange(event);
        }
        updateXMLPreview();
    });

    // 初始化popovers
    initializePopovers();
}

// 初始化应用
async function initializeApp() {
    try {
        initializeState();
        await loadPrivacyData();
        attachEventListeners();
        updateXMLPreview();
        updateNoItemsMessages();
        console.log('Available API Types:', state.apiTypes);
    } catch (error) {
        console.error('Failed to initialize app:', error);
        showError('Failed to initialize app: ' + error.message);
    }
}

// 启动应用
document.addEventListener('DOMContentLoaded', initializeApp);

// 处理API类型变化
function handleAPITypeChange(event) {
    const apiTypeContainer = event.target.closest('.api-type-item');
    if (!apiTypeContainer) return;

    const apiTypeSelect = event.target;
    const apiType = apiTypeSelect.value;
    const description = state.apiTypes.get(apiType)?.description || '';
    
    // 更新描述
    const descriptionElement = apiTypeContainer.querySelector('.api-type-description');
    if (descriptionElement) {
        descriptionElement.textContent = description;
    }

    // 更新状态
    if (!state.selectedItems.apiTypes.has(apiType)) {
        state.selectedItems.apiTypes.set(apiType, new Set());
    }

    updateXMLPreview();
}

// API 类型函数
function addAPITypeItem() {
    // 检查是否还有可添加的API类型
    const availableAPITypes = new Map([...state.apiTypes].filter(([key]) => 
        !Array.from(document.querySelectorAll('.api-type-select')).some(select => select.value === key)
    ));

    if (availableAPITypes.size === 0) {
        alert('All API Types have been added.');
        return;
    }

    const template = document.getElementById('apiTypeTemplate');
    const container = document.getElementById('apiTypesContainer');
    const clone = template.content.cloneNode(true);
    
    // 填充API类型选项
    const apiTypeSelect = clone.querySelector('.api-type-select');
    availableAPITypes.forEach((type, key) => {
        const option = document.createElement('option');
        option.value = key;
        option.textContent = type.name;
        apiTypeSelect.appendChild(option);
    });

    // 为每个API类型添加收集目的
    const purposesContainer = clone.querySelector('.api-purposes-container');
    if (purposesContainer) {
        // 从private.json获取目的列表
        const purposes = ['AppFunctionality', 'Analytics', 'ThirdPartyAdvertising'];
        purposes.forEach(purpose => {
            const typeKey = getTypeKeyForPurpose(purpose);
            const purposeItem = createPurposeItem(purpose, typeKey);
            purposesContainer.appendChild(purposeItem);
        });
    }

    // 为删除按钮添加事件监听器
    const removeButton = clone.querySelector('.remove-api-type');
    removeButton.addEventListener('click', function(event) {
        const item = event.target.closest('.api-type-item');
        const apiTypeSelect = item.querySelector('.api-type-select');
        state.selectedItems.apiTypes.delete(apiTypeSelect.value);
        item.remove();
        updateXMLPreview();
        updateNoItemsMessages();
    });

    container.appendChild(clone);
    updateNoItemsMessages();
    initializePopovers();
}

// 从private.json获取typeKey
function getTypeKeyForPurpose(purpose) {
    if (!privacyData || !privacyData.APITypes || !privacyData.APITypes.items) {
        return '';
    }

    // 遍历API类型找到对应的typeKey
    for (const category of privacyData.APITypes.items) {
        if (category.items) {
            for (const item of category.items) {
                if (item.typeKey && item.explain.toLowerCase().includes(purpose.toLowerCase())) {
                    return item.typeKey;
                }
            }
        }
    }
    return '';
}

// 生成XML预览
function updateXMLPreview() {
    const xmlPreview = document.getElementById('xmlPreview');
    if (!xmlPreview) return;

    let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
    xml += '<privacy>\n';
    
    // Tracking
    if (state.trackingEnabled) {
        xml += '    <tracking>true</tracking>\n';
    }
    
    // API Types
    const apiTypes = Array.from(state.selectedItems.apiTypes.entries());
    if (apiTypes.length > 0) {
        xml += '    <api-types>\n';
        apiTypes.forEach(([apiType, purposes]) => {
            if (purposes.size > 0) {
                xml += `        <api-type name="${apiType}">\n`;
                xml += '            <purposes>\n';
                purposes.forEach(purpose => {
                    xml += `                <purpose>${purpose}</purpose>\n`;
                });
                xml += '            </purposes>\n';
                xml += '        </api-type>\n';
            }
        });
        xml += '    </api-types>\n';
    }
    
    // Data Types
    const dataTypes = Array.from(state.selectedItems.dataTypes.entries());
    if (dataTypes.length > 0) {
        xml += '    <data-types>\n';
        dataTypes.forEach(([dataType, purposes]) => {
            if (purposes.length > 0) {
                xml += `        <data-type name="${dataType}">\n`;
                xml += '            <purposes>\n';
                purposes.forEach(purpose => {
                    xml += `                <purpose>${purpose}</purpose>\n`;
                });
                xml += '            </purposes>\n';
                xml += '        </data-type>\n';
            }
        });
        xml += '    </data-types>\n';
    }
    
    xml += '</privacy>';
    
    // 使用prismjs高亮显示
    xmlPreview.innerHTML = Prism.highlight(xml, Prism.languages.xml, 'xml');
}

// Data Collection 处理函数
function createDataPurposeItem(purpose) {
    const purposeItem = document.createElement('div');
    purposeItem.className = 'purpose-item';

    const label = document.createElement('label');
    label.className = 'form-check';

    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.className = 'form-check-input data-purpose-checkbox';
    checkbox.value = purpose.value;

    const labelContent = document.createElement('div');
    labelContent.className = 'label-content';

    const span = document.createElement('span');
    span.textContent = purpose.label;

    const infoIcon = document.createElement('i');
    infoIcon.className = 'bi bi-info-circle purpose-info';
    infoIcon.setAttribute('data-bs-toggle', 'popover');
    infoIcon.setAttribute('data-bs-trigger', 'hover focus');
    infoIcon.setAttribute('data-bs-html', 'true');
    infoIcon.setAttribute('data-bs-content', 
        `<strong>${purpose.label}</strong><br>${purpose.description}<br><br><strong>${purpose.labelChinese}</strong><br>${purpose.descriptionChinese}`);

    label.appendChild(checkbox);
    labelContent.appendChild(span);
    labelContent.appendChild(infoIcon);
    label.appendChild(labelContent);
    purposeItem.appendChild(label);

    return purposeItem;
}

function addDataTypeCard() {
    const container = document.getElementById('dataCollectionContainer');
    const noMessageEl = document.getElementById('noDataCollectionMessage');
    
    // 创建卡片容器
    const card = document.createElement('div');
    card.className = 'card mb-3 data-type-card';
    
    // 创建卡片头部
    const cardHeader = document.createElement('div');
    cardHeader.className = 'card-header bg-white d-flex align-items-center gap-3';
    
    // 创建选择器组
    const selectGroup = document.createElement('div');
    selectGroup.className = 'input-group';
    
    const select = document.createElement('select');
    select.className = 'form-select data-type-select';
    
    // 添加默认选项
    const defaultOption = document.createElement('option');
    defaultOption.value = '';
    defaultOption.textContent = 'Select Data Type';
    select.appendChild(defaultOption);
    
    // 添加数据类型选项
    const dataTypes = [
        {
            value: 'userIdentifier',
            name: 'User ID',
            description: 'Any form of user identifier',
            groupName: 'User Data'
        },
        {
            value: 'emailAddress',
            name: 'Email Address',
            description: 'User email address information',
            groupName: 'Contact Info'
        },
        {
            value: 'phoneNumber',
            name: 'Phone Number',
            description: 'User phone number information',
            groupName: 'Contact Info'
        },
        {
            value: 'deviceIdentifier',
            name: 'Device ID',
            description: 'Device identification information',
            groupName: 'Device Info'
        },
        {
            value: 'location',
            name: 'Location',
            description: 'User location information',
            groupName: 'Location Data'
        },
        {
            value: 'browsing',
            name: 'Browsing History',
            description: 'User browsing history and activity',
            groupName: 'Usage Data'
        },
        {
            value: 'contacts',
            name: 'Contacts',
            description: 'User contacts information',
            groupName: 'Contact Info'
        },
        {
            value: 'photos',
            name: 'Photos',
            description: 'User photos and media',
            groupName: 'Media'
        }
    ];

    // 按组分类并排序
    const groupedTypes = dataTypes.reduce((acc, type) => {
        if (!acc[type.groupName]) {
            acc[type.groupName] = [];
        }
        acc[type.groupName].push(type);
        return acc;
    }, {});

    // 创建选项组
    Object.keys(groupedTypes).sort().forEach(groupName => {
        const group = document.createElement('optgroup');
        group.label = groupName;
        
        groupedTypes[groupName].sort((a, b) => a.name.localeCompare(b.name)).forEach(type => {
            const option = document.createElement('option');
            option.value = type.value;
            option.textContent = type.name;
            group.appendChild(option);
        });
        
        select.appendChild(group);
    });
    
    const removeBtn = document.createElement('button');
    removeBtn.className = 'btn btn-outline-secondary';
    removeBtn.innerHTML = '<i class="bi bi-trash"></i>';
    removeBtn.onclick = function() {
        card.remove();
        if (container.children.length === 0) {
            noMessageEl.style.display = 'block';
        }
        updateXMLPreview();
    };
    
    selectGroup.appendChild(select);
    selectGroup.appendChild(removeBtn);
    cardHeader.appendChild(selectGroup);
    
    // 创建卡片内容
    const cardBody = document.createElement('div');
    cardBody.className = 'card-body';
    
    const description = document.createElement('p');
    description.className = 'data-type-description text-muted mb-3';
    
    const purposesContainer = document.createElement('div');
    purposesContainer.className = 'data-purposes-container';
    
    const purposeItems = document.createElement('div');
    purposeItems.className = 'purpose-items';
    
    // 添加默认的收集目的选项
    const purposes = [
        {
            value: 'advertising',
            label: 'Advertising or Marketing',
            labelChinese: '广告或营销',
            description: 'Used for advertising or marketing purposes, including third party advertising.',
            descriptionChinese: '用于广告或营销目的，包括第三方广告。'
        },
        {
            value: 'analytics',
            label: 'Analytics',
            labelChinese: '分析',
            description: 'Used to collect data for analytics purposes to improve app functionality.',
            descriptionChinese: '用于收集数据进行分析，以改进应用功能。'
        },
        {
            value: 'third_party_advertising',
            label: 'Third-Party Advertising',
            labelChinese: '第三方广告',
            description: 'Used for third-party advertising purposes.',
            descriptionChinese: '用于第三方广告目的。'
        },
        {
            value: 'app_functionality',
            label: 'App Functionality',
            labelChinese: '应用功能',
            description: 'Used to provide core app functionality and services.',
            descriptionChinese: '用于提供核心应用功能和服务。'
        }
    ];
    
    purposes.forEach(purpose => {
        purposeItems.appendChild(createDataPurposeItem(purpose));
    });
    
    purposesContainer.appendChild(purposeItems);
    cardBody.appendChild(description);
    cardBody.appendChild(purposesContainer);
    
    card.appendChild(cardHeader);
    card.appendChild(cardBody);
    
    container.appendChild(card);
    noMessageEl.style.display = 'none';
    
    // 初始化新卡片的popovers
    initializePopovers();
    
    // 添加事件监听
    select.addEventListener('change', handleDataTypeChange);
    purposeItems.addEventListener('change', function(event) {
        if (event.target.matches('.data-purpose-checkbox')) {
            handleDataPurposeChange(event);
        }
    });
}

function handleDataTypeChange(event) {
    const select = event.target;
    const card = select.closest('.data-type-card');
    const description = card.querySelector('.data-type-description');
    
    // 更新描述
    const selectedType = select.value;
    if (selectedType) {
        const typeInfo = dataTypes.find(type => type.value === selectedType);
        if (typeInfo) {
            description.textContent = typeInfo.description;
        }
    } else {
        description.textContent = '';
    }
    
    updateXMLPreview();
}

function handleDataPurposeChange(event) {
    const checkbox = event.target;
    const card = checkbox.closest('.data-type-card');
    const select = card.querySelector('.data-type-select');
    const selectedType = select.value;
    
    if (selectedType) {
        const purposes = Array.from(card.querySelectorAll('.data-purpose-checkbox'))
            .filter(cb => cb.checked)
            .map(cb => cb.value);
        
        state.selectedItems.dataTypes.set(selectedType, purposes);
        updateXMLPreview();
    }
}

function handleDataTypeRemove(event) {
    if (!event.target.matches('.remove-data-type') && !event.target.closest('.remove-data-type')) return;
    
    const item = event.target.closest('.data-collection-item');
    const select = item.querySelector('.data-type-select');
    state.selectedItems.dataTypes.delete(select.value);
    
    item.remove();
    updateNoItemsMessages();
    updateXMLPreview();
}

// 辅助函数
function updateNoItemsMessages() {
    const apiTypesContainer = document.getElementById('apiTypesContainer');
    const dataCollectionContainer = document.getElementById('dataCollectionContainer');
    const noAPITypesMessage = document.getElementById('noAPITypesMessage');
    const noDataCollectionMessage = document.getElementById('noDataCollectionMessage');

    if (noAPITypesMessage) {
        noAPITypesMessage.style.display = 
            apiTypesContainer.querySelector('.api-type-item') ? 'none' : 'block';
    }

    if (noDataCollectionMessage) {
        noDataCollectionMessage.style.display = 
            dataCollectionContainer.querySelector('.data-collection-item') ? 'none' : 'block';
    }
}

function updateTrackingState(event) {
    state.trackingEnabled = event.target.checked;
    updateXMLPreview();
}

// XML 生成和预览
function generateXML() {
    let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
    xml += '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n';
    xml += '<plist version="1.0">\n';
    xml += '<dict>\n';

    // API Types
    if (state.selectedItems.apiTypes.size > 0) {
        xml += '    <key>NSPrivacyAccessedAPITypes</key>\n';
        xml += '    <array>\n';
        state.selectedItems.apiTypes.forEach((purposes, apiType) => {
            if (purposes && purposes.length > 0) {
                xml += '        <dict>\n';
                xml += `            <key>NSPrivacyAccessedAPIType</key>\n`;
                xml += `            <string>${apiType}</string>\n`;
                xml += '            <key>NSPrivacyAccessedAPITypeReasons</key>\n';
                xml += '            <array>\n';
                purposes.forEach(purpose => {
                    xml += `                <string>${purpose}</string>\n`;
                });
                xml += '            </array>\n';
                xml += '        </dict>\n';
            }
        });
        xml += '    </array>\n';
    }

    // 添加数据类型和目的
    if (state.selectedItems.dataTypes.size > 0) {
        xml += '    <key>NSPrivacyCollectedDataTypes</key>\n';
        xml += '    <array>\n';
        state.selectedItems.dataTypes.forEach((purposes, dataType) => {
            xml += '        <dict>\n';
            xml += `            <key>NSPrivacyCollectedDataType</key>\n`;
            xml += `            <string>${dataType}</string>\n`;
            
            // 添加目的
            if (purposes.length > 0) {
                xml += '            <key>NSPrivacyCollectedDataTypePurposes</key>\n';
                xml += '            <array>\n';
                purposes.forEach(purpose => {
                    xml += `                <string>${purpose}</string>\n`;
                });
                xml += '            </array>\n';
            }
            
            xml += '        </dict>\n';
        });
        xml += '    </array>\n';
    }

    // 添加跟踪信息
    if (state.trackingEnabled) {
        xml += '    <key>NSPrivacyTrackingDomains</key>\n';
        xml += '    <array>\n';
        xml += '        <string>example.com</string>\n';
        xml += '    </array>\n';
    }

    xml += '</dict>\n';
    xml += '</plist>';

    document.getElementById('xmlPreview').textContent = xml;
}

const debouncedUpdateXMLPreview = debounce(() => {
    const xml = generateXML();
    elements.xmlPreview.textContent = xml;
    hljs.highlightElement(elements.xmlPreview);
}, 300);

function updateXMLPreview() {
    debouncedUpdateXMLPreview();
}

// 实用函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function initializePopovers() {
    // 初始化所有的popovers
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl, {
            container: 'body',
            placement: 'auto',
            trigger: 'hover focus',
            html: true
        });
    });

    // 当点击复选框或标签时阻止popover显示
    document.addEventListener('click', (event) => {
        if (event.target.matches('.api-purpose-checkbox') || 
            event.target.matches('.form-check-label:not(.purpose-info)')) {
            const popoverTrigger = event.target.closest('.purpose-item').querySelector('.purpose-info');
            const popover = bootstrap.Popover.getInstance(popoverTrigger);
            if (popover) {
                popover.hide();
            }
        }
    });
}

function getPurposeDescription(purpose) {
    switch (purpose) {
        case 'advertising':
            return 'Used for advertising or marketing purposes, including third party advertising.';
        case 'analytics':
            return 'Used to collect data for analytics purposes to improve app functionality.';
        case 'third_party_advertising':
            return 'Used for third-party advertising purposes.';
        case 'app_functionality':
            return 'Used to provide core app functionality and services.';
        default:
            return '';
    }
}

function getPurposeTranslation(purpose) {
    switch (purpose) {
        case 'advertising':
            return '广告或营销';
        case 'analytics':
            return '分析';
        case 'third_party_advertising':
            return '第三方广告';
        case 'app_functionality':
            return '应用功能';
        default:
            return '';
    }
}

function getPurposeTranslationDescription(purpose) {
    switch (purpose) {
        case 'advertising':
            return '用于广告或营销目的，包括第三方广告。';
        case 'analytics':
            return '用于收集数据进行分析，以改进应用功能。';
        case 'third_party_advertising':
            return '用于第三方广告目的。';
        case 'app_functionality':
            return '用于提供核心应用功能和服务。';
        default:
            return '';
    }
}
